package com.blog.cloud.gateway.handler;

import com.blog.cloud.core.utils.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 网关服务全局异常处理
 *
 * @author 龙茶清欢
 * @since 2022-10-08 00:13:17
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
    private final ObjectMapper objectMapper;
    @NotNull
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, @NotNull Throwable ex) {
        // 对异常的响应格式进行统一设置
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        // 设置响应格式为JSON
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (ex instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) ex).getStatusCode());
        }
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                log.info("error in spring cloud gateway,the request path is :{},the error message is {}", exchange.getRequest().getPath(), ex.getMessage());
                return bufferFactory.wrap(
                        objectMapper.writeValueAsBytes(R.failed(ex.getMessage()))
                );
            } catch (JsonProcessingException e) {
                log.error("error when writing response with exception message", ex);
                return bufferFactory.wrap(e.getMessage().getBytes(StandardCharsets.UTF_8));
            }
        }));
    }

    // 参考ErrorWebExceptionHandler默认实现和的源码
}
